package main

import (
	"fmt"
	"strconv"
	"strings"

	m "gitee.com/chenhonghua/common-service/cmd/segment/model"
	"gitee.com/chenhonghua/ginorigin/env"
	"gitee.com/chenhonghua/ginorigin/http/restful"
	"gitee.com/chenhonghua/ginorigin/http/router"
	"gitee.com/chenhonghua/ginorigin/log"
	"github.com/gin-gonic/gin"

	"github.com/huichen/sego"
)

var (
	DICS      = env.StringVal("SEGO_DICT_FILES", "./files/tag.txt,./files/dict.big.txt,./files/dict.custom.txt")
	segmenter sego.Segmenter
)

func init() {
	segmenter.LoadDictionary(DICS)
	segmenter.Dictionary()
	restful.RegisterErrorFromCodeAndMessage(10001, "参数错误：文本不能为空")
}

// 分词服务
func main() {
	router.RouterConfig{
		Enable:    true,
		LogEnable: true,
		AllowCors: true,
	}.Load()
	router.SetWriter(log.DefaultLogger.Out)
	v1Group := router.GetRouter().Group("/api/v1")
	v1Group.GET("health", restful.Success) // 健康检测
	v1Group.GET("seg", HANDLER)            // 分词

	if e := router.GetRouter().Run(fmt.Sprintf("0.0.0.0:%d", env.IntVal("SERVER_PORT", 58782))); e != nil {
		log.Fatal(e)
	}
}

// 文本分词服务
//
// 请求参数:
//
//	w: 文本
var HANDLER gin.HandlerFunc = func(ctx *gin.Context) {
	text := strings.TrimSpace(ctx.Query("text"))
	if len(text) == 0 {
		restful.Errors.FromCode(10001)
		return
	}
	isSearchMod, e := strconv.ParseBool(strings.TrimSpace(ctx.Query("is_search_mod")))
	if e != nil {
		isSearchMod = false
	}
	r := segmenter.InternalSegment([]byte(text), isSearchMod)
	var texts []m.Text = make([]m.Text, 0)
	for _, v := range r {
		t := m.NewText(v.Token().Text(), v.Token().Pos())
		if isSearchMod {
			if !t.Pos.Meaningful {
				continue
			}
		}
		texts = append(texts, t)
	}
	restful.Data(ctx, texts)
}
